package basicutil.pipeline.core;

import basicutil.pipeline.DataMessage;
import basicutil.pipeline.DataType;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

public class OutputPort {

    private final String portId;
    private final DataType dataType;
    private final BlockingQueue<DataMessage> inputQueue;

    AtomicBoolean beConnected = new AtomicBoolean(false);

    private int maxQueueSize;        // 最大队列大小
    // todo 分流模式
private List<InputPort> connectPorts ;
    public OutputPort(String portId, DataType dataType) {
        this.portId = portId;
        this.dataType = dataType;
        this.inputQueue = new LinkedBlockingQueue<>();
        this.maxQueueSize = 1000;
        connectPorts = new ArrayList<>();
    }


    public boolean canConnect(InputPort other) {
        return other != null &&
                this.dataType.equals(other.getDataType());
    }


    public void connectTo(InputPort other) {
        if(!connectPorts.contains(other)){
            connectPorts.add(other);
        }

    }

    public void receiveMessage(DataMessage message) {
        if (inputQueue.size() < maxQueueSize) {
            inputQueue.offer(message);
        } else {
            System.err.println("Queue full in node " + portId + ", message dropped");
        }
    }

    public String getId() {
        return portId;
    }


    public DataType getDataType() {
        return dataType;
    }


    public boolean isConnected() {
        return beConnected.get();
    }

    public void setMaxQueueSize(int maxQueueSize) {
        this.maxQueueSize = maxQueueSize;
    }
}

